<template>
  <div>
    <div class="search-container">
      <div class="search-inp-container">
        <el-select
          @keyup.enter.native="handleSearch"
          v-model="listQuery.typeId"
          placeholder="选择物资类型"
          style="width:170px"
          clearable
        >
          <el-option
            v-for="item in typeList"
            :key="item.typeId"
            :label="item.typeName"
            :value="item.typeId"
          >
            <span style="float: left">{{ item.typeName }}</span>
          </el-option>
        </el-select>
      </div>
      <el-button
        class="search-btn"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >{{$t('m.QUERY')}}</el-button>
      <el-button
        class="search-btn"
        type="primary"
        icon="el-icon-plus"
        v-if="mall_ad_add"
        @click="handleAdd"
      >{{$t('m.ADD')}}</el-button>
      <el-button
        class="search-btn"
        :autofocus="true"
        icon="el-icon-refresh"
        @click="refreshHandle"
      >{{$t('m.REFRESH')}}</el-button>
    </div>
    <el-table :key="tableKey" :data="list" v-loading="listLoading" border fit highlight-current-row>
      <el-table-column align="center" prop="typeName" :label="$t('m.TYPE_NAME')"></el-table-column>
      <el-table-column align="center" prop="suppliesNum" :label="$t('m.MATERIALS_NUM')"></el-table-column>
      <el-table-column align="center" prop="suppliesName" :label="$t('m.MATERIALS_NAME')"></el-table-column>
      <!-- <el-table-column align="center" prop="status" :label="$t('m.MATERIALS_STATUS')">
        <template slot-scope="scope">
          <span>{{scope.row.status | statusFilter}}</span>
        </template>
      </el-table-column>-->
      <el-table-column align="center" :label="$t('m.CREATE_TIME')">
        <template slot-scope="scope">
          <span>{{scope.row.createTime }}</span>
          <!-- <span>{{scope.row.createTime | parseTime('{y}-{m}-{d} {h}:{i}')}}</span> -->
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        :label="$t('m.OPERATION')"
        width="300"
        v-if="mall_ad_del  || mall_ad_update "
      >
        <template align="center" slot-scope="scope">
          <el-button
            v-if="mall_ad_update"
            size="mini"
            type="primary"
            @click="handleGet(scope.row)"
          >{{$t('m.VIEW')}}</el-button>
          <el-button
            v-if="mall_ad_update"
            size="mini"
            type="primary"
            @click="handleEdit(scope.row)"
          >{{$t('m.EDIT')}}</el-button>
          <el-button
            v-if="mall_ad_del"
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
          >{{$t('m.DELECT')}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="listQuery.current"
        :page-size="listQuery.size"
        :page-sizes="[10, 40, 80, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="40%"
      :close-on-click-modal="false"
      @close="cancel('form')"
    >
      <div style="height:500px">
        <el-scrollbar ref="myScrollbar" style="height:100%" wrap-style="overflow-x:hidden;">
          <el-form
            :model="form"
            :rules="rules"
            ref="form"
            label-width="100px"
            enctype="multipart/form-data"
          >
            <el-form-item :label="$t('m.TYPE_NAME')" prop="typeId">
              <el-select
                class="filter-item w347"
                v-model="form.typeId"
                placeholder="请选择"
                @change="changeType(form.type)"
                :disabled="disabled"
              >
                <el-option
                  v-for="item in typeList"
                  :key="item.typeId"
                  :label="item.typeName"
                  :value="item.typeId"
                >
                  <span style="float: left">{{ item.typeName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              class="w347"
              :label="$t('m.MATERIALS_NUM')"
              placeholder="请输入物资编号"
              prop="suppliesNum"
            >
              <el-input v-model="form.suppliesNum" maxlength="20" :disabled="disabled"></el-input>
            </el-form-item>
            <el-form-item
              class="w347"
              :label="$t('m.MATERIALS_NAME')"
              placeholder="请输入物资名称"
              prop="suppliesName"
            >
              <el-input v-model="form.suppliesName" maxlength="12" :disabled="disabled"></el-input>
            </el-form-item>

            <el-form-item :label="$t('m.PERSON_IN_CHARGE_INFORMATION')" prop="isShow">
              <el-form-item label prop="isShow">
                <el-button
                  v-if="!disabled"
                  type="primary"
                  @click="addDomainPerson($event)"
                >{{$t('m.ADD_PERSON')}}</el-button>
              </el-form-item>
            </el-form-item>

            <div v-for="(person,index) in form.personList" :key="person.key">
              <el-form-item
                class="w347"
                :label="$t('m.PERSON_NAME')"
                placeholder="请输入负责人名称"
                :prop="`personList[${index}].personName`"
                :rules="personRules.personName"
              >
                <el-input
                  v-model="person.personName"
                  maxlength="12"
                  :disabled="disabled"
                  style="width: 40%"
                ></el-input>
                <el-button
                  v-if="!disabled"
                  type="primary"
                  @click.prevent="removeDomainPerson(person)"
                >{{$t('m.DELECT')}}</el-button>
              </el-form-item>
              <el-form-item :label="$t('m.PICTURE')">
                <div>
                  <el-upload
                    class="avatar-uploader1"
                    :action="imgUpload"
                    :headers="headers"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess.bind(this,index)"
                    :before-upload="beforeAvatarUpload"
                    :disabled="disabled"
                  >
                    <img v-if="person.pic" :src="person.pic" class="avatar1" />
                    <i
                      v-else
                      class="el-icon-plus avatar-uploader-icon1"
                      style="border: 1px dashed #d9d9d9;"
                    ></i>
                  </el-upload>
                </div>
              </el-form-item>
              <el-form-item
                class="w347"
                :label="$t('m.PHONE')"
                placeholder="请输入负责人电话"
                :prop="`personList[${index}].personTel`"
                :rules="personRules.personTel"
              >
                <el-input
                  v-model="person.personTel"
                  maxlength="12"
                  :disabled="disabled"
                  style="width: 40%"
                ></el-input>
              </el-form-item>
              <el-form-item
                class="w347"
                :label="$t('m.DEPARTMENT')"
                placeholder="请输入部门名称"
                prop="title"
              >
                <el-input
                  v-model="person.groupName"
                  maxlength="20"
                  :disabled="disabled"
                  style="width: 40%"
                ></el-input>
              </el-form-item>
              <el-form-item class="w347" :label="$t('m.AGE')" placeholder="请输入年龄" prop="title">
                <el-input
                  v-model="person.age"
                  maxlength="12"
                  :disabled="disabled"
                  style="width: 40%"
                ></el-input>
              </el-form-item>
              <el-form-item class="w347" :label="$t('m.DUTY')" placeholder="请输入职务" prop="title">
                <el-input
                  v-model="person.dutyName"
                  maxlength="20"
                  :disabled="disabled"
                  style="width: 40%"
                ></el-input>
              </el-form-item>
            </div>

            <el-form-item :label="$t('m.MATERIALS_PROP')" prop="isShow">
              <el-form-item label prop="isShow">
                <el-button
                  v-if="!disabled"
                  type="primary"
                  @click="addDomain($event)"
                >{{$t('m.ADD_PROP')}}</el-button>
              </el-form-item>
            </el-form-item>

            <el-form-item v-for="(domain,index) in form.propList" :key="domain.key">
              <el-form-item>
                <template>
                  <el-col>
                    <label>{{$t('m.NAME')}}</label>
                    <el-input
                      v-model="domain.propName"
                      placeholder
                      @input="change($event)"
                      style="width: 30%"
                      :disabled="disabled"
                    ></el-input>
                    <label>{{$t('m.VALUE')}}</label>
                    <el-input
                      v-model="domain.propData"
                      placeholder
                      @input="change($event)"
                      style="width: 30%"
                      :disabled="disabled"
                    ></el-input>
                    <el-button
                      v-if="!disabled"
                      type="primary"
                      @click.prevent="removeDomain(domain)"
                    >{{$t('m.DELECT')}}</el-button>
                  </el-col>
                </template>
              </el-form-item>
            </el-form-item>

            <el-form-item :label="$t('m.REAL_TIME_DATA')" prop="messCode">
              <el-input
                class="w347"
                style="white-space: pre-line;"
                v-model="form.suppliesRealnfo"
                placeholder
                rows="5"
                type="textarea"
                maxlength="300"
                disabled="disabled"
              ></el-input>
            </el-form-item>
            <el-form-item :label="$t('m.RELATED_MATERIALS')" prop="reSuppliesId">
              <el-select
                class="filter-item w347"
                v-model="form.reSuppliesId"
                placeholder="请选择"
                :disabled="disabled"
                style="width: 40%"
                clearable
              >
                <el-option
                  v-for="item in suppliesList"
                  :key="item.videoID"
                  :label="item.videoName"
                  :value="item.videoID"
                >
                  <span style="float: left">{{ item.videoName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-scrollbar>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')">{{$t('m.CANCEL')}}</el-button>
        <el-button
          v-if="dialogStatus=='create' && !disabled"
          type="primary"
          @click="create('form')"
        >{{$t('m.CONFIRM')}}</el-button>
        <el-button
          v-if="dialogStatus=='update' && !disabled"
          type="primary"
          @click="update('form')"
        >{{$t('m.UPDATE')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchList,
  delObj,
  getObj,
  addObj,
  putObj,
  getToken,
  getTypeList,
} from '@/api/supplies'
import { getVideo, dataflow } from '@/api/idispatch'
import { mapGetters } from 'vuex'
import { Message } from 'element-ui'
export default {
  data() {
    return {
      imageUrl: '',
      tableKey: 0,
      listLoading: false,
      list: [],
      orgOptions: [],
      listQuery: {
        current: 1,
        size: 10,
        typeId: '',
        // desc: 'create_date'
      },
      total: 0,
      mall_ad_add: true,
      mall_ad_update: true,
      mall_ad_del: true,
      sys_user_select: false,
      dialogFormVisible: false,
      typeShow: true,
      // 图片
      dialogImageUrl: undefined,
      dialogVisible: false,
      fileList: [],
      url: '',
      imgUpload: process.env.BASE_API + '/person/imgUpload/',
      headers: {
        Authorization: getToken(),
        // token为系统访问需要的,放在header中
      },
      form: {
        typeId: undefined,
        suppliesNum: undefined,
        suppliesName: undefined,
        reSuppliesId: undefined,
        personList: [
          {
            personName: undefined,
            personTel: undefined,
            pic: undefined,
            age: undefined,
            groupName: undefined,
            dutyName: undefined,
          },
        ],
        propList: [
          {
            propName: undefined,
            propData: undefined,
          },
        ],
      },
      rules: {
        typeId: [
          { required: true, message: '请选择物资类型', trigger: 'change' },
        ],
        suppliesNum: [
          { required: true, message: '请输入物资编号', trigger: 'blur' },
        ],
        suppliesName: [
          { required: true, message: '请输入物资名称', trigger: 'blur' },
        ],
      },
      personRules: {
        personName: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
        ],
        personTel: [
          { required: true, message: '电话不能为空', trigger: 'blur' },
        ],
      },
      textMap: {
        update: '编辑',
        create: '创建',
        get: '查看',
      },
      dialogStatus: '',
      role: [],
      typeOptions: [],
      isShowOptions: [],
      isDisabled: {
        0: false,
        1: true,
      },
      statusOptions: ['0', '1'],
      dialogDeptVisible: false,
      treeDeptData: [],
      checkedKeys: [],
      typeList: [],
      disabled: false,
      suppliesList: [],
    }
  },

  components: {},
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: '离线',
        1: '在线',
        9: '锁定',
      }
      return statusMap[status]
    },
  },
  computed: {
    ...mapGetters(['permissions']),
  },

  mounted() {
    this.init()
    this.getList()
    // this.mall_ad_add = this.permissions['/mall/ad:add']
    // this.mall_ad_update = this.permissions['/mall/ad:update']
    // this.mall_ad_del = this.permissions['/mall/ad:del']
    // this.sys_user_select = this.permissions['/admin/user:select']
    getTypeList({ current: 1, size: 9999 }).then((res) => {
      this.typeList = res.data.records
    })
  },

  created() {
    // 把本地方法注册到外部，客户端容器才能调用
    window.MapDataPush = this.MapDataPush
  },

  methods: {
    init() {
      // 客户端嵌入网页，通知客户端，地图加载完成，开始推送数据
      const type = sessionStorage.getItem('type')
      if (type === 'idispatch') {
        window.external.MapLoadedEvent()
      } else {
        this.getVideo()
      }
    },
    /**
     * 客户端数据推送接口
     */
    MapDataPush(type, data, isFirst) {
      console.log('MapDataPush 客户端数据推送接口', type)
      this.MapDataDeal(type, data, isFirst)
      // remoteLog({ type, data, isFirst })
    },
    // 处理地图推送数据
    MapDataDeal(type, data, isFirst) {
      switch (type) {
        case 'videogroup':
          break
        case 'group':
          break
        case 'video':
          this.PushVideo(data, isFirst)
          break
        case 'operator':
          break
        case 'employee':
          break
        default:
          break
      }
    },
    // 推送摄像头
    PushVideo(data, isFirst) {
      this.suppliesList = JSON.parse(data).data
    },
    getList() {
      this.listLoading = true
      this.listQuery.isAsc = false
      fetchList(this.listQuery).then((response) => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
        if (this.listQuery.current != 1 && this.list.length == 0) {
          this.listQuery.current = this.listQuery.current - 1
          this.getList()
        }
      })
    },
    // 取物资下拉框
    getSuppilesList() {
      fetchList(this.listQuery).then((response) => {
        this.suppliesList = response.data.records
      })
    },
    // 取调度台摄像头（蹲点仪器信息）
    getVideo() {
      getVideo({}).then((res) => {
        if (res.msg === 'fail') {
          Message({
            message: '调度台已退出，请重新登录',
            type: 'error',
          })
        } else {
          this.suppliesList = res.data.data.cameras
        }
      })
    },
    addDomain(e) {
      this.form.propList.push({
        propName: undefined,
        propData: undefined,
        key: Date.now(),
      })
      this.$forceUpdate()
    },
    addDomainPerson(e) {
      this.form.personList.push({
        personName: undefined,
        personTel: undefined,
        pic: undefined,
        age: undefined,
        groupName: undefined,
        dutyName: undefined,
        key: Date.now(),
      })
      this.$forceUpdate()
    },
    refreshHandle() {
      this.listQuery.current = 1
      this.listQuery.size = 10
      this.listQuery.typeId = ''
      this.getList()
      this.init()
    },
    handleAdd() {
      this.form = {
        propList: [
          {
            propData: undefined,
            propName: undefined,
          },
        ],
        personList: [
          {
            personName: undefined,
            personTel: undefined,
            pic: undefined,
            age: undefined,
            groupName: undefined,
            dutyName: undefined,
          },
        ],
      }
      this.imageUrl = ''
      this.dialogStatus = 'create'
      this.disabled = false
      getTypeList({ current: 1, size: 9999 }).then((res) => {
        this.typeList = res.data.records
      })
      this.dialogFormVisible = true
    },
    handleDelete(row) {
      this.$confirm(this.$t('m.tip.DELECT_TIP'), this.$t('m.tip.TIPS'), {
        confirmButtonText: this.$t('m.CONFIRM'),
        cancelButtonText: this.$t('m.CANCEL'),
        type: 'warning',
      }).then(() => {
        delObj(row.suppliesId)
          .then(() => {
            this.getList()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000,
            })
          })
          .cache(() => {
            this.$notify({
              title: '失败',
              message: '删除失败',
              type: 'error',
              duration: 2000,
            })
          })
      })
    },
    handleEdit(row) {
      this.dialogStatus = 'update'
      this.disabled = false
      getTypeList({ current: 1, size: 9999 }).then((res) => {
        this.typeList = res.data.records
      })
      getObj(row.suppliesId).then((response) => {
        this.form = response.data
        this.form.typeId = String(this.form.typeId)
        // 图片回显
        const obj = new Object()
        if (response.data.personList.length > 0) {
          obj.url = response.data.personList[0].pic
          if (obj.url != null) {
            this.imageUrl = obj.url
          }
        } else {
          this.form.personList = [
            {
              personName: undefined,
              personTel: undefined,
              pic: undefined,
              age: undefined,
              groupName: undefined,
              dutyName: undefined,
            },
          ]
        }
        this.dialogFormVisible = true
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
      })
    },
    handleGet(row) {
      this.dialogStatus = 'get'
      this.disabled = true
      getTypeList({ current: 1, size: 9999 }).then((res) => {
        this.typeList = res.data.records
      })
      getObj(row.suppliesId).then((response) => {
        this.form = response.data
        this.form.typeId = String(this.form.typeId)
        // 图片回显
        const obj = new Object()
        if (response.data.personList.length > 0) {
          obj.url = response.data.personList[0].pic
          if (obj.url != null) {
            this.imageUrl = obj.url
          }
        } else {
          this.form.personList = [
            {
              personName: undefined,
              personTel: undefined,
              pic: undefined,
              age: undefined,
              groupName: undefined,
              dutyName: undefined,
            },
          ]
        }
        this.dialogFormVisible = true
        this.dialogStatus = 'get'
        this.dialogFormVisible = true
      })
    },
    handleSearch() {
      this.listQuery.current = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.current = val
      this.getList()
    },
    create(formName) {
      if (this.form.personList.length === 0) {
        this.$notify({
          title: '失败',
          message: '至少绑定一个负责人',
          type: 'error',
          duration: 2000,
        })
        return
      }
      for (let i = 0; i < this.form.personList.length; i++) {
        const element = this.form.personList[i]
        if (element.personName === '' || element.personName == undefined) {
          this.$notify({
            title: '失败',
            message: '请填写负责人姓名',
            type: 'error',
            duration: 2000,
          })
          return
        }
      }
      const set = this.$refs
      set[formName].validate((valid) => {
        if (valid) {
          addObj(this.form).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000,
            })
          })
        } else {
          return false
        }
      })
    },
    cancel(formName) {
      this.dialogFormVisible = false
      this.$refs[formName].resetFields()
    },
    update(formName) {
      const _this = this
      const set = this.$refs
      set[formName].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false
          putObj(this.form).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000,
            })
            // 修改关联的摄像头
            if (
              _this.form.reSuppliesId != '' &&
              _this.form.reSuppliesId != undefined &&
              _this.form.reSuppliesId != null
            ) {
              const videoArr = _this.suppliesList.filter((e) => {
                return e.videoID == _this.form.reSuppliesId
              })
              if (videoArr.length === 0) {
                return
              }
              const type = sessionStorage.getItem('type')
              if (type !== 'idispatch') {
                const obj = videoArr[0]
                obj['@id'] = '100000'
                obj['@type'] = 'VideoInfoMod'
                obj['videoName'] = _this.form.suppliesName
                const form = {
                  request: obj,
                }
                dataflow(form).then((res) => {
                  console.log('同步修改请求发起：' + res.data.msg)
                })
              }
            }
          })
        } else {
          return false
        }
      })
    },
    change(e) {
      this.$forceUpdate()
    },

    removeDomain(item) {
      var index = this.form.propList.indexOf(item)
      if (index !== -1) {
        this.form.propList.splice(index, 1)
      }
      this.$forceUpdate()
    },
    removeDomainPerson(item) {
      var index = this.form.personList.indexOf(item)
      if (index !== -1) {
        this.form.personList.splice(index, 1)
      }
      this.$forceUpdate()
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    handleAvatarSuccess(index, res, file) {
      var url = res.true
      if (url == '' || url == undefined || url == 'undefined') {
        this.$notify({
          title: '失败',
          message: res.false,
          type: 'error',
          duration: 2000,
        })
        return
      }
      this.form.personList[index].pic = url // 表单提交
      this.form.personList[index].pic = URL.createObjectURL(file.raw)
    },
  },
}
</script>


<style lang='scss' scoped>
.w347 {
  width: 100%;
}
.avatar-uploader1 .el-upload1 {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader1 .el-upload:hover1 {
  border-color: #409eff;
}
.avatar-uploader-icon1 {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar1 {
  width: 200px;
  height: 178px;
  display: block;
}
</style>

